from fetchemApp.models import *
import smtplib
import threading

def reg_notify(arg, course):
    try:
        smtpserver = smtplib.SMTP("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
    except:
        return 'CONNECTION ERROR'
    
    try:
        user = course.SubEmail
        pwd = course.SubPassword
        smtpserver.login(user, pwd)
    except:
        return 'AUTHENTICATION ERROR'
    
    if len(arg)<1:
        return 'EMPTY LIST'
    
    sub = "Registration in "  + course.CourseNo + ' ' + course.Name
    
    if type(arg[0]) == type(Student()):
        for stud in arg:
            to = stud.Email
            I = course.Graders.filter(Type='I')[0]
            header = 'To:' + to + '\n' + 'From: ' + user + '\n' + 'Subject:' + sub + '\n'
            body = 'You have been registered as a student for ' + course.CourseNo + ' ' + course.Name +' in Fetch\'em.'
            body += ' If this is a mistake, please contact the instructor, ' + I.Name + ' at ' + I.Email
            body += "\n\nCheers,\nTeam Fetch'em"
            msg = header + '\n' + body
            smtpserver.sendmail(user, to, msg)
    else:
        if type(arg[0]) == type(Grader()):
            for grdr in arg:
                to = grdr.Email
                I = course.Graders.filter(Type='I')[0]
                header = 'To:' + to + '\n' + 'From: ' + user + '\n' + 'Subject:' + sub + '\n'
                body = 'You have been registered as a TA for ' + course.CourseNo + ' ' + course.Name +' in Fetch\'em.'
                body += ' If this is a mistake, please contact the instructor, ' + I.Name + ' at ' + I.Email
                body += "\n\nCheers,\nTeam Fetch'em"
                msg = header + '\n' + body
                smtpserver.sendmail(user, to, msg)

    return 'SUCCESS'
    smtpserver.close()
    
def SendRegistrationNotice(PeopleList, CourseObject):
    try:
        T = threading.Thread(target=reg_notify, kwargs={'arg': PeopleList, 'course': CourseObject})
        T.start()
    except:
        return False
    return True